package com.ligq.h265toupinpush.toupin

import android.Manifest
import android.app.Activity
import android.content.Context
import android.media.projection.MediaProjection
import android.media.projection.MediaProjectionManager
import android.os.Bundle
import android.widget.Toast
import androidx.activity.result.contract.ActivityResultContracts
import androidx.appcompat.app.AppCompatActivity
import com.ligq.common.utils.PermissionUtils
import com.ligq.h265toupinpush.R

class MainActivity : AppCompatActivity() {
    private lateinit var mediaProjection: MediaProjection
    private lateinit var socketLive: SocketLive
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)
        if (PermissionUtils.permissionGranted(Manifest.permission.WRITE_EXTERNAL_STORAGE)) {
            createMediaProjection()
        } else {
            Toast.makeText(this, "no permission!!", Toast.LENGTH_SHORT).show()
        }
    }

    private fun createMediaProjection() {
        val projectionManager =
            getSystemService(Context.MEDIA_PROJECTION_SERVICE) as MediaProjectionManager?
        val createScreenCaptureIntent = projectionManager?.createScreenCaptureIntent()
        registerForActivityResult(ActivityResultContracts.StartActivityForResult()) { activityResult ->
            if (activityResult.resultCode != Activity.RESULT_OK) {
                return@registerForActivityResult
            }
            mediaProjection =
                activityResult.data?.let { intent ->
                    projectionManager?.getMediaProjection(
                        activityResult.resultCode,
                        intent
                    )
                }!!
            start()
        }.launch(createScreenCaptureIntent)
    }

    private fun start() {
        if (this::mediaProjection.isInitialized) {
            socketLive = SocketLive()
            socketLive.start(0, mediaProjection)
        } else {
            Toast.makeText(this, "录屏失败，请重试！！", Toast.LENGTH_SHORT).show()
        }
    }

    override fun onDestroy() {
        super.onDestroy()
        if (this::socketLive.isInitialized) {
            socketLive.close()
        }
    }

}